<script setup lang="ts">
import { ref } from 'vue'
import { ElInput, ElSelect, ElOption, ElButton, ElMessage } from 'element-plus'

const props = defineProps<{
  visible: boolean
}>()

const emit = defineEmits(['update:visible', 'confirm'])

// 表单数据
const formData = ref({
  displayName: '', // 数据源显示名称
  host: '', // 数据源地址
  port: '', // 端口
  encoding: 'utf8', // 编码
  database: '', // 数据库名称
  username: '', // 用户名
  password: '' // 密码
})

// 编码选项
const encodingOptions = [
  { value: 'utf8', label: 'UTF-8' },
  { value: 'gbk', label: 'GBK' },
  { value: 'ascii', label: 'ASCII' }
]

// 添加当前步骤状态
const currentStep = ref(1)

// 数据源类型列表
const sourceTypes = [
  {
    type: 'cloud',
    title: '云数据库',
    items: [
      { id: 'mysql', name: '云数据库 MySQL', icon: 'database', color: '#1890ff' },
      { id: 'mysql-c', name: '云数据库 TDSQL-C MySQL版', icon: 'cloud', color: '#13227a' },
      { id: 'tdsql', name: '分布式数据库 TDSQL MySQL版', icon: 'cubes', color: '#1677ff' },
      { id: 'sqlserver', name: '云数据库 SQLServer', icon: 'window-maximize', color: '#0078d4' }
    ]
  },
  {
    type: 'warehouse',
    title: '数据仓库',
    items: [
      { id: 'postgresql', name: '云数据库 PostgreSQL', icon: 'database', color: '#336791' },
      { id: 'mariadb', name: '云数据库 MariaDB', icon: 'database', color: '#C0765A' }
    ]
  }
]

// 选中的数据源类型
const selectedSourceType = ref('')

// 处理选择数据源类型
const handleSelectType = (typeId: string) => {
  selectedSourceType.value = typeId
  currentStep.value = 2
}

// 返回类型选择
const backToTypeSelect = () => {
  currentStep.value = 1
  selectedSourceType.value = ''
}

// 重置表单
const resetForm = () => {
  formData.value = {
    displayName: '',
    host: '',
    port: '',
    encoding: 'utf8',
    database: '',
    username: '',
    password: ''
  }
}

// 测试连接
const testConnection = async () => {
  try {
    // TODO: 调用测试连接接口
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('连接成功')
  } catch (error) {
    ElMessage.error('连接失败')
  }
}

// 确认创建
const handleConfirm = async () => {
  if (!formData.value.displayName.trim()) {
    ElMessage.warning('请输入数据源显示名称')
    return
  }
  if (!formData.value.host.trim()) {
    ElMessage.warning('请输入数据源地址')
    return
  }
  if (!formData.value.port.trim()) {
    ElMessage.warning('请输入端口号')
    return
  }
  if (!formData.value.database.trim()) {
    ElMessage.warning('请输入数据库名称')
    return
  }
  
  try {
    // TODO: 调用创建数据源接口
    await new Promise(resolve => setTimeout(resolve, 1000))
    emit('confirm', formData.value)
    closeDialog()
    ElMessage.success('创建成功')
  } catch (error) {
    ElMessage.error('创建失败')
  }
}

// 关闭对话框
const closeDialog = () => {
  emit('update:visible', false)
  resetForm()
  currentStep.value = 1
  selectedSourceType.value = ''
}
</script>

<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="emit('update:visible', $event)"
    :title="currentStep === 1 ? '选择数据源类型' : '新建数据源'"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="closeDialog"
  >
    <!-- 步骤指示器 -->
    <div class="step-header">
      <div class="step" :class="{ active: currentStep >= 1 }">
        <div class="step-number">
          <i v-if="currentStep > 1" class="fa fa-check"></i>
          <template v-else>1</template>
        </div>
        <span>选择类型</span>
      </div>
      <div class="step-line"></div>
      <div class="step" :class="{ active: currentStep >= 2 }">
        <div class="step-number">2</div>
        <span>配置数据源</span>
      </div>
    </div>

    <!-- 类型选择页面 -->
    <div v-if="currentStep === 1" class="type-selection">
      <div v-for="group in sourceTypes" :key="group.type" class="type-group">
        <h3 class="group-title">{{ group.title }}</h3>
        <div class="type-grid">
          <div
            v-for="item in group.items"
            :key="item.id"
            class="type-item"
            :style="{ '--type-color': item.color }"
            @click="handleSelectType(item.id)"
          >
            <div class="type-icon">
              <i :class="['fa', `fa-${item.icon}`]"></i>
            </div>
            <div class="type-name">{{ item.name }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 配置表单页面 -->
    <div v-else class="datasource-form">
      <div class="form-content">
        <div class="form-item">
          <div class="label">数据源显示名称 <span class="required">*</span></div>
          <el-input
            v-model="formData.displayName"
            placeholder="请输入数据源显示名称"
          />
        </div>

        <div class="form-item">
          <div class="label">数据源地址 <span class="required">*</span></div>
          <el-input
            v-model="formData.host"
            placeholder="请输入数据源地址（Host）"
          />
        </div>

        <div class="form-item">
          <div class="label">端口 <span class="required">*</span></div>
          <el-input
            v-model="formData.port"
            placeholder="请输入端口号"
          />
        </div>

        <div class="form-item">
          <div class="label">编码</div>
          <el-select v-model="formData.encoding" class="full-width">
            <el-option
              v-for="option in encodingOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </div>

        <div class="form-item">
          <div class="label">数据库名称 <span class="required">*</span></div>
          <el-input
            v-model="formData.database"
            placeholder="请输入数据库名称，例如：test_bi_db"
          />
        </div>

        <div class="form-item">
          <div class="label">用户名</div>
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
          />
        </div>

        <div class="form-item">
          <div class="label">密码</div>
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <template v-if="currentStep === 2">
          <el-button @click="backToTypeSelect">上一步</el-button>
          <el-button @click="testConnection">测试连接</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </template>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.datasource-form {
  padding: 20px 0;
}

.step-header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 32px;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #909399;
}

.step.active {
  color: #409eff;
}

.step-number {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: #f5f7fa;
  border: 1px solid currentColor;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.step.active .step-number {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.step-line {
  width: 100px;
  height: 1px;
  background: #e4e7ed;
  margin: 0 20px;
  margin-bottom: 28px;
}

.form-content {
  max-width: 480px;
  margin: 0 auto;
}

.form-item {
  margin-bottom: 24px;
}

.form-item .label {
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
}

.required {
  color: #f56c6c;
  margin-left: 4px;
}

.full-width {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
}

.type-selection {
  padding: 20px 0;
}

.type-group {
  margin-bottom: 32px;
}

.group-title {
  font-size: 16px;
  color: #303133;
  margin: 0 0 16px 0;
}

.type-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 16px;
}

.type-item {
  --type-color: #1890ff;
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.type-item:hover {
  border-color: var(--type-color);
  background: rgba(var(--type-color), 0.02);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.type-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: var(--type-color);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.type-name {
  font-size: 14px;
  color: #606266;
}

.type-item:hover .type-name {
  color: var(--type-color);
}
</style> 